package com.enation.app.javashop.manager.api.distribution;

import com.enation.app.javashop.core.base.context.Region;
import com.enation.app.javashop.core.base.context.RegionFormat;
import com.enation.app.javashop.core.base.model.vo.SuccessMessage;
import com.enation.app.javashop.core.distribution.exception.DistributionErrorCode;
import com.enation.app.javashop.core.distribution.exception.DistributionException;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.dto.AuditDistributionDTO;
import com.enation.app.javashop.core.distribution.model.vo.DistributionVO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.system.sendMessage.WechatSendMessage;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 后台分销商管理
 *
 * @author Chopper
 * @version v1.0
 * @Description:
 * @since v7.0
 * 2018/5/25 上午10:55
 */
@RestController
@RequestMapping("/admin/distribution/member")
@Api(description = "分销商")
public class DistributionManagerController {

    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private WechatSendMessage wechatSendMessage;

    protected final Log logger = LogFactory.getLog(this.getClass());

    @ApiOperation("分销商列表")
    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_size", value = "页码大小", required = false, paramType = "query", dataType = "int", allowMultiple = false),
            @ApiImplicitParam(name = "page_no", value = "页码", required = false, paramType = "query", dataType = "int", allowMultiple = false),
    })
    public Page<DistributionVO> page(DistributionVO distributionVO, @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize,@RegionFormat @RequestParam(value = "index_region", required = false) Region region) {
        try {
            if(region != null){
                distributionVO.setProvinceId(region.getProvinceId());
                distributionVO.setCityId(region.getCityId());
                distributionVO.setCountyId(region.getCountyId());
            }
            return distributionManager.page(pageNo, pageSize, distributionVO);
        } catch (DistributionException e) {
            throw e;
        } catch (Exception e) {
            logger.error("获取模版异常：", e);
            throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
        }
    }


    @ApiOperation("修改模版")
    @PutMapping("/tpl")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "member_id", value = "会员ID", required = true, paramType = "query", dataType = "int", allowMultiple = false),
            @ApiImplicitParam(name = "tpl_id", value = "模版id", required = true, paramType = "query", dataType = "int", allowMultiple = false),
    })
    public void changeTpl(@ApiIgnore Integer memberId, @ApiIgnore Integer tplId) throws Exception {
        if (memberId == null || tplId == null) {
            throw new DistributionException(DistributionErrorCode.E1011.code(), DistributionErrorCode.E1011.des());
        }
        try {
            distributionManager.changeTpl(memberId, tplId);
        } catch (DistributionException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改模版异常：", e);
            throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
        }
    }

    @PutMapping(value = "/audit")
    @ApiOperation("审核分销商")
    public SuccessMessage audit(AuditDistributionDTO auditDTO,@RegionFormat @RequestParam(value = "index_region", required = false) Region region) {
        try {
            Integer auditStatus = auditDTO.getAuditStatus();
            DistributionDO distributionDO = distributionManager.getDistributorByMemberId(auditDTO.getMemberId());
            distributionDO.setAuditStatus(auditStatus);
            String statusName = auditStatus == 2 ? "审核通过" : "审核不通过";
            distributionDO.setStatusName(statusName);
            distributionDO.setAuditTime(DateUtil.getDateline());
            distributionDO.setAuditRemark(auditDTO.getRefuseReason());
            distributionDO.setOperateAreas(auditDTO.getOperateAreas());
            distributionDO.setWechatGroupsNum(auditDTO.getWechatGroupsNum());

            // 三级地址
            if(region != null){
                distributionDO.setProvinceId(region.getProvinceId());
                distributionDO.setProvince(region.getProvince());
                distributionDO.setCityId(region.getCityId());
                distributionDO.setCity(region.getCity());
                distributionDO.setCountyId(region.getCountyId());
                distributionDO.setCounty(region.getCounty());
            }
            // 详细地址
            distributionDO.setAddress(auditDTO.getAddress());
//            Integer teamNaemNum = distributionManager.getTeamName(distributionDO.getProvinceId());
            // 团号
            String teamName = auditDTO.getTeamName();
            if(StringUtil.notEmpty(teamName)){
                if(!teamName.contains("团")){
                    teamName = teamName +"团";
                }
            }
            distributionDO.setTeamName(teamName);
            // 查询团号是否在该地区已存在
            Boolean typeNameBoolean = distributionManager.queryTeamNameNum(distributionDO);
            if(!typeNameBoolean){
                return new SuccessMessage("【 "+teamName+" 】,已存在!");
            }
            distributionManager.edit(distributionDO);
            //推送团长审核通知消息
            try {
                wechatSendMessage.sendDistributionMessage(distributionDO);
            }catch (Exception e){
                logger.error("发送团长审核记录：", e);
            }
            return new SuccessMessage("审核成功");

        } catch (Exception e) {
            logger.error("审核分销商出错", e);
            throw new DistributionException(DistributionErrorCode.E1000.code(), DistributionErrorCode.E1000.des());
        }
    }


    @PostMapping(value = "/update_lv1_member_id")
    @ApiOperation("修改上级团长")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "member_ids", value = "需要修改的memberId", required = true, dataType = "String"),
        @ApiImplicitParam(name = "member_id_lv1", value = "上级团长的memberId", required = true, dataType = "int")
    })
    public SuccessMessage updateLv1MemberId( @ApiIgnore String memberIds, @ApiIgnore Integer memberIdLv1) {

        try {
            distributionManager.updateLv1MemberId(memberIds, memberIdLv1);
            return new SuccessMessage("操作成功");
        } catch (Exception e) {
            logger.error("上级团长更新失败", e);
            throw new DistributionException("-1", "上级团长更新失败" + e.getMessage());
        }
    }

    @GetMapping(value = "/query_distribution")
    @ApiOperation("查询团长")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key_words", value = "邀请码,团长姓名,团长手机号", required = true, paramType = "query", dataType = "String")})
    public Page queryDistribution(@ApiIgnore String keyWords) {
        return distributionManager.getSuperiorDistribution(keyWords);
    }

    @PostMapping(value = "/open_or_close")
    @ApiOperation("启用或禁用")
    public SuccessMessage openOrClose(String distributionIds, Integer status) {
        try {
            distributionManager.updateDistributionStatus(distributionIds,status);
            return new SuccessMessage("操作成功");
        } catch (Exception e) {
            logger.error("启用或禁用出错", e);
            throw new DistributionException("-1", "启用或禁用出错" + e.getMessage());
        }
    }

    @PutMapping(value = "/audit_dis_data")
    @ApiOperation("修改团长信息")
    public SuccessMessage auditDisData(AuditDistributionDTO auditDTO,@RegionFormat @RequestParam(value = "index_region", required = false) Region region) {
        try {
            DistributionDO distributionDO = distributionManager.getDistributorByMemberId(auditDTO.getMemberId());
            distributionDO.setAuditTime(DateUtil.getDateline());
            distributionDO.setOperateAreas(auditDTO.getOperateAreas());
            distributionDO.setWechatGroupsNum(auditDTO.getWechatGroupsNum());

            // 三级地址
            if(region != null){
                distributionDO.setProvinceId(region.getProvinceId());
                distributionDO.setProvince(region.getProvince());
                distributionDO.setCityId(region.getCityId());
                distributionDO.setCity(region.getCity());
                distributionDO.setCountyId(region.getCountyId());
                distributionDO.setCounty(region.getCounty());
            }
            // 详细地址
            distributionDO.setAddress(auditDTO.getAddress());
            // 团号
            String teamName = auditDTO.getTeamName();
            if(StringUtil.notEmpty(teamName)){
                if(!teamName.contains("团")){
                    teamName = teamName +"团";
                }
            }
            distributionDO.setTeamName(teamName);
            // 查询团号是否在该地区已存在
            Boolean typeNameBoolean = distributionManager.queryTeamNameNum(distributionDO);
            if(!typeNameBoolean){
                return new SuccessMessage("【 "+teamName+" 】,已存在!");
            }
            distributionManager.edit(distributionDO);
            return new SuccessMessage("操作成功");
        } catch (Exception e) {
            logger.error("修改团长信息失败", e);
            throw new DistributionException("-1", "修改团长信息失败" + e.getMessage());
        }
    }

}
